<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\admin\model\RouteModel;
use app\portal\Tool\Tool;
use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\admin\model\ThemeModel;
use think\facade\Db;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Cell;

class AdminOrderController extends AdminBaseController
{

    /**
     * 页面管理
     * @adminMenu(
     *     'name'   => '页面管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '页面管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('portal_admin_page_index_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();
        $xhpage = $this->request->param('page', 1, 'intval');
        $pagenum = !empty($param['pagenum']) ? $param['pagenum'] : 10;
        if ($xhpage > 1) {
            $xhpage = ($xhpage - 1) * $pagenum + 1;
        } else {
            $xhpage = 1;
        }
        $this->assign('xhpage', $xhpage);

        $postService = new PostService();
        $data = $postService->adminOrderList($param);

        $moneyArray = [];

        if(isset($param['gdstatus']) && $param['gdstatus'] == '已完成')
        {
            $items = $data->toArray()['data'];
            $portalPostModel = new PortalPostModel();
            foreach ($items as $item)
            {
                $id = $item['id'];
                $post_title = $item['post_title'];
                $post_title = '用户：（' . $post_title . '）在工单：（' . $id . '）的扣费';
                $portalPost = $portalPostModel->where('post_title', $post_title)->find();
                $money = $portalPost['more']['money'];
                $moneyArray[] = $money;
            }
        }

        $ageArray = [];
        $sexArray = [];
        $olderTypeArray = [];
        $portalPostModel = new PortalPostModel();
        foreach ($data->toArray()['data'] as $item)
        {
            $zjnum = '';
            if(isset($item['more']['zjnum']))
            {
                $zjnum = $item['more']['zjnum'];
                $birthday = substr($zjnum, 6, 8);
                $age = Tool::getYearsPassed($birthday);
                $ageArray[] = $age;
            }
            else
            {
                $ageArray[] = '';
            }
            $sex = $item['more']['sex'];
            $sexArray[] = $sex;

            $subData = $portalPostModel
                ->where('JSON_UNQUOTE(JSON_EXTRACT(`more`, "$.zjnum")) = "'.$zjnum . '"')
                ->where('post_type', 3)
                ->where('delete_time', 0)
                ->field('more')
                ->find();
			$butieType = '';
			if(isset($subData['more']['butietype']))
			{
				$butieType = $subData['more']['butietype'];
			}
            $olderTypeArray[] = $butieType;
        }

        //echo $data;
        // print_r($data);
        // foreach ($data as $datas) {
        //     $xm = $datas['more']['xm'];
        //     //$datas['xm'] = $xm;
        //     //if($xm){
        //         $xm = json_decode($xm,true);
        //         $datas['xm'] = $datas['more']['xm'];
        //     //}
        // }
        $data->appends($param);

        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('zjnum', isset($param['zjnum']) ? $param['zjnum'] : '');
        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('start_finish_time', isset($param['start_finish_time']) ? $param['start_finish_time'] : '');
        $this->assign('end_finish_time', isset($param['end_finish_time']) ? $param['end_finish_time'] : '');
        $this->assign('gdstatus', isset($param['gdstatus']) ? $param['gdstatus'] : '');
        $this->assign('pagenum', isset($param['pagenum']) ? $param['pagenum'] : 10);
        $this->assign('pages', $data->items());
        $this->assign('page', $data->render());
        $this->assign('moneyArray', $moneyArray);
        $this->assign('ageArray', $ageArray);
        $this->assign('sexArray', $sexArray);
        $this->assign('olderTypeArray', $olderTypeArray);

        return $this->fetch();
    }

    /**
     * 门店所属订单统计管理
     * @adminMenu(
     *     'name'   => '页面管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '页面管理',
     *     'param'  => ''
     * )
     */
    public function mdorderlist()
    {
        $content = hook_one('portal_admin_page_index_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();
        $xhpage = $this->request->param('page', 1, 'intval');
        if ($xhpage > 1) {
            $xhpage = ($xhpage - 1) * 10 + 1;
        } else {
            $xhpage = 1;
        }
        $this->assign('xhpage', $xhpage);
        $mdname = $this->request->param('mdname', '', 'intval');
        if ($mdname) { //根据门店名称查门店id
            $smd = Db::name('portal_post')->where('post_title', $mdname)->find();
            $param['fwmdid'] = $smd['id'];
        }
        $strats = $this->request->param('strats', 0, 'intval');
        $postService = new PostService();
        //$param['fwmdid'] = $fwmdid;
        $data = $postService->adminOrderList($param);
        $data->appends($param);

        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('pages', $data->items());
        $this->assign('page', $data->render());
        $this->assign('strats', $strats);
        return $this->fetch();
    }

    /**
     * 添加页面
     * @adminMenu(
     *     'name'   => '添加页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加页面',
     *     'param'  => ''
     * )
     */
    public function getxmlist()
    {
        $id = $this->request->param('id', 0, 'intval');
        $xmlist = Db::name('portal_tag')
            ->alias("t")
            ->join('ylpt_portal_tag_post p', 't.id = p.tag_id')
            ->field('t.*')
            ->where('t.price', '>', 0)
            ->where('p.post_id', '=', $id)->select();
        //return $xmlist;
        $this->success('成功', '', $xmlist);
    }

    public function add()
    {
        $content = hook_one('portal_admin_page_add_view');

        if (!empty($content)) {
            return $content;
        }

        $param = $this->request->param();

        //项目列表
        //$xmlist = Db::name('portal_tag')->where('price', '>', 0)->select();

        $id = $this->request->param('id', 0, 'intval');
        $portalPostModel = new PortalPostModel();
        $post = $portalPostModel->where('id', $id)->find();
        $postCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $flinfo = Db::name('portal_category')->where('id', $postCategoryIds)->find();
        $dlinfo = Db::name('portal_category')->where('id', $flinfo['parent_id'])->find();
        $this->assign('dlname', $dlinfo['name']);
        $themeModel = new ThemeModel();
        $pageThemeFiles = $themeModel->getActionThemeFiles('portal/Page/index');
        $this->assign('page_theme_files', $pageThemeFiles);
        $this->assign('laoren', $post);
        $this->assign('xmlist', []);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);
        $this->assign('category', isset($param['category']) ? $param['category'] : '');
        $this->assign('page', isset($param['page']) ? $param['page'] : '');
        return $this->fetch();
    }

    /**
     * 添加页面提交
     * @adminMenu(
     *     'name'   => '添加页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加页面提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        $data = $this->request->param();
        $data['post']['post_title'] = $data['laoren']['post_title'];
        $data['post']['czlrid'] = $data['laoren']['id'];
        $data['post']['more']['tel'] = $data['laoren']['more']['tel'];
        $data['post']['more']['sex'] = $data['laoren']['more']['sex'];
        $data['post']['more']['age'] = $data['laoren']['more']['age'];
        $data['post']['more']['zjnum'] = $data['laoren']['more']['zjnum'];
        $data['post']['post_type'] = 5;
        $ddh = date('YmdHis', time()) . '' . rand(1000, 9999);
        $data['post']['post_source'] = $ddh;
        //$data['post']['more']['add'] = $data['laoren']['more']['add'];
        $result = $this->validate($data['post'], 'AdminPage');
        if ($result !== true) {
            $this->error($result);
        }
        $portalPostModel = new PortalPostModel();
        // $laoreninfo = $portalPostModel->where('id', $data['post']['czlrid'])->find(); //获取残疾人余额
        // if($data['post']['money'] > $laoreninfo['money']){
        //     $this->error("余额不足，请充值");
        // }

        if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
            $data['post']['more']['photos'] = [];
            foreach ($data['photo_urls'] as $key => $url) {
                $photoUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
            }
        }

        if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            $data['post']['more']['files'] = [];
            foreach ($data['file_urls'] as $key => $url) {
                $fileUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            }
        }
        //print_r($data['post']); exit;

        $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);
        //扣费记录
        //改变残疾人账号余额
        // $laorendata['id'] = $data['post']['czlrid'];
        // $laorendata['money'] = intval($laoreninfo['money']) - intval($data['post']['money']);
        // $gdinfo = $portalPostModel->adminEditChongzhi($laorendata);
        // //增加扣费记录

        // $chongzhi['user_id'] = cmf_get_current_admin_id();
        // $chongzhi['create_time'] = time();
        // $chongzhi['update_time'] = time();
        // $chongzhi['published_time'] = time();
        // $chongzhi['post_title'] = $data['post']["post_title"]."工单：（".$gdinfo['id']."）扣费";
        // $chongzhi['czlrid'] = $laorendata["id"];
        // $chongzhi['post_type'] = 4;
        // $chongzhi['more'] = [
        //                             'money' => $laorendata["money"],
        //                             'oldmoney' => $laoreninfo['money'],
        //                             'addmoney' => "-".$data['post']['money']
        // ];
        // Db::name('portal_post')->json(['more'])->insert($chongzhi);
        //$this->error('13');
        $this->success(lang('ADD_SUCCESS'), url('AdminLaoren/gdlrlist', array('category'=>$data['category'], 'page'=>$data['page'])));

    }

    /**
     * 编辑页面
     * @adminMenu(
     *     'name'   => '编辑页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $content = hook_one('portal_admin_page_edit_view');

        if (!empty($content)) {
            return $content;
        }

        //项目列表


        $id = $this->request->param('id', 0, 'intval');

        $portalPostModel = new PortalPostModel();
        $post = $portalPostModel->where('id', $id)->find();
        $laoren = $portalPostModel->where('id', $post['czlrid'])->find();
        $laorenCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
        $laorenCategoryIds = implode(',', array_keys($laorenCategories));
        $postCategories = $post->tags()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $flinfo = Db::name('portal_category')->where('id', $laorenCategoryIds)->find();
        $dlinfo = Db::name('portal_category')->where('id', $flinfo['parent_id'])->find();
        $this->assign('dlname', $dlinfo['name']);
        $themeModel = new ThemeModel();
        $pageThemeFiles = $themeModel->getActionThemeFiles('portal/Page/index');

        $routeModel = new RouteModel();
        $alias = $routeModel->getUrl('portal/Page/index', ['id' => $id]);
        $post['post_alias'] = $alias;
        //echo $postCategoryIds;
        $xmlist = Db::name('portal_tag')
            ->alias("t")
            ->join('ylpt_portal_tag_post p', 't.id = p.tag_id')
            ->field('t.*')
            ->where('t.price', '>', 0)
            ->where('p.post_id', '=', $post['fwmdid'])->select();
        $this->assign('page_theme_files', $pageThemeFiles);
        $this->assign('post', $post);
        $this->assign('laoren', $laoren);
        $this->assign('xmlist', $xmlist);
        $this->assign('laoren_categories', $laorenCategories);
        $this->assign('laoren_category_ids', $laorenCategoryIds);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);
        return $this->fetch();
    }

    /**
     * 编辑页面提交
     * @adminMenu(
     *     'name'   => '编辑页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        $data = $this->request->param();
        $data['post']['post_title'] = $data['laoren']['post_title'];
        $data['post']['czlrid'] = $data['laoren']['id'];
        $data['post']['more']['tel'] = $data['laoren']['more']['tel'];
        $data['post']['more']['sex'] = $data['laoren']['more']['sex'];
        $data['post']['more']['age'] = $data['laoren']['more']['age'];
        $data['post']['more']['zjnum'] = $data['laoren']['more']['zjnum'];
        //$data['post']['more']['add'] = $data['laoren']['more']['add'];
        $result = $this->validate($data['post'], 'AdminPage');
        if ($result !== true) {
            $this->error($result);
        }

        if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
            $data['post']['more']['photos'] = [];
            foreach ($data['photo_urls'] as $key => $url) {
                $photoUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
            }
        }

        if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            $data['post']['more']['files'] = [];
            foreach ($data['file_urls'] as $key => $url) {
                $fileUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            }
        }
        // print_r($data['post']); exit;
        $portalPostModel = new PortalPostModel();

        $portalPostModel->adminEditArticle($data['post'], $data['post']['categories']);

        $this->success(lang('SAVE_SUCCESS'), url('AdminOrder/index'));

    }

    /**
     * 派单页面
     * @adminMenu(
     *     'name'   => '编辑页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面',
     *     'param'  => ''
     * )
     */
    public function paidan()
    {
        $content = hook_one('portal_admin_page_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');
        $ck = $this->request->param('ck', 0, 'intval');

        $portalPostModel = new PortalPostModel();
        $post = $portalPostModel->where('id', $id)->find();
        $laoren = $portalPostModel->where('id', $post['czlrid'])->find();
        $laorenCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
        $laorenCategoryIds = implode(',', array_keys($laorenCategories));
        $postCategories = $post->tags()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $flinfo = Db::name('portal_category')->where('id', $laorenCategoryIds)->find();
        $dlinfo = Db::name('portal_category')->where('id', $flinfo['parent_id'])->find();
        $this->assign('dlname', $dlinfo['name']);

        $themeModel = new ThemeModel();
        $pageThemeFiles = $themeModel->getActionThemeFiles('portal/Page/index');

        $routeModel = new RouteModel();
        $alias = $routeModel->getUrl('portal/Page/index', ['id' => $id]);
        $post['post_alias'] = $alias;
        $this->assign('page_theme_files', $pageThemeFiles);
        $this->assign('post', $post);
        $this->assign('laoren', $laoren);
        $this->assign('laoren_categories', $laorenCategories);
        $this->assign('laoren_category_ids', $laorenCategoryIds);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);
        $this->assign('ck', $ck);
        return $this->fetch();
    }

    /**
     * 编辑页面提交
     * @adminMenu(
     *     'name'   => '编辑页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面提交',
     *     'param'  => ''
     * )
     */
    public function paidanPost()
    {
        $data = $this->request->param();
        if ($data['post']['more']['mendianfwy'] == '') {
            $this->error("请选择服务人员");
        }
        //$this->error($data['post']['more']['gdstarttime']);
        $portalPostModel = new PortalPostModel();
        $laoreninfo = $portalPostModel->where('id', $data['laoren']['id'])->find(); //获取残疾人余额

        if ($data['post']['gdstatus'] == "已录单" or $data['post']['gdstatus'] == "已退款") {
            if ($data['post']['money'] > $laoreninfo['money']) {
                $this->error("余额不足，请充值");
            }
            //扣费记录
            //改变残疾人账号余额
            $laorendata['id'] = $data['laoren']['id'];
            //$laorendata['money'] = intval($laoreninfo['money']) - intval($data['post']['money']);
            $laorendata['money'] = round($laoreninfo['money']*1 - $data['post']['money']*1, 2);
            $gdinfo = $portalPostModel->adminEditChongzhi($laorendata);
            //增加扣费记录

            $chongzhi['user_id'] = cmf_get_current_admin_id();
            $chongzhi['create_time'] = time();
            $chongzhi['update_time'] = time();
            $chongzhi['published_time'] = time();
            $chongzhi['post_title'] = "用户：（" . $data['laoren']["post_title"] . "）在工单：（" . $data['post']['id'] . "）的扣费";
            $chongzhi['czlrid'] = $laorendata["id"];
            $chongzhi['post_type'] = 4;
            $chongzhi['more'] = [
                'money' => $laorendata["money"],
                'oldmoney' => $laoreninfo['money'],
                'addmoney' => "-" . $data['post']['money']
            ];
            Db::name('portal_post')->json(['more'])->insert($chongzhi);
        }
        $data['post']['gdstatus'] = '待接单';
        $data['post']['more']['tel'] = $data['laoren']['more']['tel'];
        $data['post']['more']['sex'] = $data['laoren']['more']['sex'];
        $data['post']['more']['age'] = $data['laoren']['more']['age'];
        $data['post']['more']['zjnum'] = $data['laoren']['more']['zjnum'];
        if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
            $data['post']['more']['photos'] = [];
            foreach ($data['photo_urls'] as $key => $url) {
                $photoUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
            }
        }

        if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            $data['post']['more']['files'] = [];
            foreach ($data['file_urls'] as $key => $url) {
                $fileUrl = cmf_asset_relative_url($url);
                array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            }
        }


        $data['post']['post_status'] = 1;
        $portalPostModel->adminEditOrder($data['post']);


        $this->success(lang('SAVE_SUCCESS'), url('AdminOrder/index'));

    }

    /**
     * 审核页面
     * @adminMenu(
     *     'name'   => '编辑页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面',
     *     'param'  => ''
     * )
     */
    public function shenhe()
    {
        $content = hook_one('portal_admin_page_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');
        $ck = $this->request->param('ck', 0, 'intval');

        $portalPostModel = new PortalPostModel();
        $post = $portalPostModel->where('id', $id)->find();
        $laoren = $portalPostModel->where('id', $post['czlrid'])->find();
        $laorenCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
        $laorenCategoryIds = implode(',', array_keys($laorenCategories));
        $postCategories = $post->tags()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));

        $themeModel = new ThemeModel();
        $pageThemeFiles = $themeModel->getActionThemeFiles('portal/Page/index');

        $routeModel = new RouteModel();
        $alias = $routeModel->getUrl('portal/Page/index', ['id' => $id]);
        $post['post_alias'] = $alias;
        $post['fwymore'] = json_decode($post['fwymore'], true);
        $fwimg = $post['fwymore']['fwimg'];
        $post['fwimg'] = explode(";", $fwimg);
        $this->assign('page_theme_files', $pageThemeFiles);
        $this->assign('post', $post);
        $this->assign('laoren', $laoren);
        $this->assign('laoren_categories', $laorenCategories);
        $this->assign('laoren_category_ids', $laorenCategoryIds);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);
        $this->assign('ck', $ck);
        $this->assign('CMF_DATA', CMF_DATA);

        return $this->fetch();
    }

    /**
     * 审核工单提交
     * @adminMenu(
     *     'name'   => '编辑页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面提交',
     *     'param'  => ''
     * )
     */
    public function shenhePost()
    {
        $data = $this->request->param();

        $data['post']['gdstatus'] = '已完成';

        Db::name('portal_post')->where('id', $data['post']['id'])
            ->update([
                'gdstatus' => $data['post']['gdstatus'],
                'finish_time' => time()
            ]);

        $this->success(lang('SAVE_SUCCESS'));

    }

    /**
     * 删除服务照片
     *
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function imgDeletePost()
    {
        $data = $this->request->param();
        $id = $data['deleteId'];
        $fwimg = $data['fwimg'];
        $fwimg = str_replace('../../storage/', '', $fwimg);
        $portalPostModel = new PortalPostModel();
        $portalPostModel = $portalPostModel->where('id', $id)->find();
        $portalPostArray = $portalPostModel->toArray();
        $fwymore = $portalPostArray['fwymore'];
        $fwymore = json_decode($fwymore, true);
        $fwimgString = $fwymore['fwimg'];
        $fwimgArray = explode(';', $fwimgString);
        foreach($fwimgArray as $key => $item)
        {
            if($fwimgArray[$key] == $fwimg)
            {
                unset($fwimgArray[$key]);
            }
        }
        $fwymore['fwimg'] = implode(';', $fwimgArray);
        $fwymore = json_encode($fwymore);
        $portalPostModel->save(['fwymore' => $fwymore]);
        if (file_exists('storage/' . $fwimg)) {
            unlink('storage/' . $fwimg);
        }
        $this->success(lang('SAVE_SUCCESS'));
    }

    /**
     * 添加服务照片
     *
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function imgAddPost()
    {
        $data = $this->request->param();
        $id = $data['addId'];
        $fwimg = $data['fwimg'];
        $fwimg = str_replace('/storage/', '', $fwimg);
        $portalPostModel = new PortalPostModel();
        $portalPostModel = $portalPostModel->where('id', $id)->find();
        $portalPostArray = $portalPostModel->toArray();
        $fwymore = $portalPostArray['fwymore'];
        $fwymore = json_decode($fwymore, true);
        $fwimgString = $fwymore['fwimg'];
        if(empty($fwimgString))
        {
            $fwymore['fwimg'] = $fwimg;
        }
        else
        {
            $fwimgArray = explode(';', $fwimgString);
            $fwimgArray[] = $fwimg;
            $fwymore['fwimg'] = implode(';', $fwimgArray);
        }
        $fwymore = json_encode($fwymore);
        $portalPostModel->save(['fwymore' => $fwymore]);
        $this->success(lang('SAVE_SUCCESS'));
    }

    /**
     * 更新服务时间
     *
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function gdstarttimeUpdatePost()
    {
        $data = $this->request->param();
        if ($data['post']['more']['gdstarttime'] == '') {
            $this->error("请选择服务时间");
        }
        $portalPost = PortalPostModel::find($data['id']);
        $updateData = $portalPost->toArray();
        $updateData['more']['gdstarttime'] = $data['post']['more']['gdstarttime'];
        $result = $portalPost->save(['more' => $updateData['more']]);
        $this->success(lang('SAVE_SUCCESS'));
    }

    /**
     * 退款
     * @adminMenu(
     *     'name'   => '编辑页面提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑页面提交',
     *     'param'  => ''
     * )
     */
    public function tuikuanPost()
    {
        $data = $this->request->param();

        $data['post']['gdstatus'] = '已退款';
        $portalPostModel = new PortalPostModel();
        $gdinfo = $portalPostModel->where('id', $data['id'])->find(); //获取残疾人余额
        $laoreninfo = $portalPostModel->where('id', $gdinfo['czlrid'])->find(); //获取残疾人余额
        //扣费记录
        //改变残疾人账号余额
        $laorendata['id'] = $laoreninfo['id'];
        $laorendata['money'] = intval($laoreninfo['money']) + intval($gdinfo['money']);

        //增加扣费记录

        $chongzhi['user_id'] = cmf_get_current_admin_id();
        $chongzhi['create_time'] = time();
        $chongzhi['update_time'] = time();
        $chongzhi['published_time'] = time();
        $chongzhi['post_title'] = "用户：（" . $gdinfo["post_title"] . "）在工单：（" . $data['id'] . "）的退款";
        $chongzhi['czlrid'] = $laorendata["id"];
        $chongzhi['post_type'] = 4;
        $chongzhi['more'] = [
            'money' => $laorendata["money"],
            'oldmoney' => $laoreninfo['money'],
            'addmoney' => $gdinfo['money']
        ];
        Db::name('portal_post')->json(['more'])->insert($chongzhi);

        $gdinfos = $portalPostModel->adminEditChongzhi($laorendata);
        Db::name('portal_post')->where('id', $data['id'])->update(['gdstatus' => $data['post']['gdstatus']]);


        $this->success(lang('SAVE_SUCCESS'));

    }

    /**
     * 删除页面
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $portalPostModel = new PortalPostModel();
        $data = $this->request->param();

        $result = $portalPostModel->adminDeletePage($data);
        if ($result) {
            $this->success(lang('DELETE_SUCCESS'));
        } else {
            $this->error(lang('DELETE_FAILED'));
        }

    }

    /**
     * 导出所有工单
     * @author    iyting@foxmail.com
     * @adminMenu(
     *     'name'   => '删除页面',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除页面',
     *     'param'  => ''
     * )
     */
    public function daochu()
    {

        $param = $this->request->param();
        //print_r($param);
        //引入PHPExcel库文件
        //vendor("PHPExcel.PHPExcel");
        //创建对象
        $excel = new PHPExcel();
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S');
        //表头数组
        $tableheader = array('序号', '工单编号', '残疾人姓名', '性别',  '残疾等级',  '联系方式', '身份证号', '年龄', '余额', '街道', '社区', '地址', '家政服务项目', '项目明细', '工单状态', '门店', '服务员姓名', '服务员电话', '总价格');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        //表格数组
        // $data = array(
        //     array('1', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('2', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('3', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('4', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('5', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('6', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('7', 'B', 'C', 'D', 'E', 'F', 'G'),
        // );
        $portalPostModel = new PortalPostModel();
        $data2 = $portalPostModel->with('categories')
            ->where('post_type', 5)
            ->where('delete_time', 0)
            ->where(function ($query) use ($param) {
                if (isset($param['start_time']) && $param['start_time']) {
                    $query->where('published_time', '>=', strtotime($param['start_time']));
                }
                if (isset($param['end_time']) && $param['end_time']) {
                    $query->where('published_time', '<=', strtotime($param['end_time']));
                }
                if (isset($param['start_finish_time']) && $param['start_finish_time']) {
                    $query->where('finish_time', '>=', strtotime($param['start_finish_time']));
                }
                if (isset($param['end_finish_time']) && $param['end_finish_time']) {
                    $query->where('finish_time', '<=', strtotime($param['end_finish_time']));
                }
                if (isset($param['keyword']) && $param['keyword']) {
                    $query->where('post_title', 'like', "%{$param['keyword']}%");
                }
                if (isset($param['zjnum']) && $param['zjnum']) {
                    $query->where('post_title', 'like', "%{$param['zjnum']}%");
                }
                if (isset($param['dcid']) && $param['dcid']) {
                    $query->whereIn('id', $param['dcid']);
                }
                if (isset($param['gdstatus']) && $param['gdstatus']) {
                    $query->whereIn('gdstatus', $param['gdstatus']);
                }
            })
            ->order("update_time desc")
            ->select();

//        dd($portalPostModel->getLastSql());

        $data2 = collect($data2)->toArray();

        $ageArray = [];
        $sexArray = [];
        $olderTypeArray = [];
        $portalPostModel = new PortalPostModel();
        foreach ($data2 as $item)
        {			
            $zjnum = '';
            if(isset($item['more']['zjnum']))
            {
                $zjnum = $item['more']['zjnum'];
                $birthday = mb_substr($zjnum, 6, 4) . mb_substr($zjnum, 10, 2)
                    . mb_substr($zjnum, 12, 2);
                $age = Tool::getYearsPassed($birthday);
                $ageArray[] = $age;
            }
            else
            {
                $ageArray[] = '';
            }
            $sex = $item['more']['sex'];
            $sexArray[] = $sex;

            $subData = $portalPostModel
                ->where('JSON_UNQUOTE(JSON_EXTRACT(`more`, "$.zjnum")) = "'.$zjnum . '"')
                ->where('post_type', 3)
                ->where('delete_time', 0)
                ->field('more')
                ->find();
            $butieType = '';
			if(isset($subData['more']['butietype']))
			{
				$butieType = $subData['more']['butietype'];
			}
            $olderTypeArray[] = $butieType;
        }

        $moneyArray = [];
        $portalPostModel = new PortalPostModel();
        foreach ($data2 as $item)
        {
            $id = $item['id'];
            $post_title = $item['post_title'];
            $post_title = '用户：（' . $post_title . '）在工单：（' . $id . '）的扣费';
            $portalPost = $portalPostModel->where('post_title', $post_title)->find();
            if(isset($portalPost['more']['money']))
            {
                $money = $portalPost['more']['money'];
                $moneyArray[] = $money;
            }
            else
            {
                $moneyArray[] = '';
            }
        }
//        dd($data2);

        // //填充表格信息
        for ($i = 2; $i <= count($data2) + 1; $i++) {
            //$infoarr = json_decode($data2[$i - 2]['more']);
            $infoarr = $data2[$i - 2]['more'];
            $tel = '';
            if (array_key_exists("tel", $infoarr)) {
                $tel = $infoarr['tel'];
            }
            if (array_key_exists("mendian", $infoarr)) {
                //$fwinfoarr = json_decode($data2[$i-2]['fwymore']);
                $mendian = $infoarr['mendian'];
                $mendianfwy = array_key_exists("mendianfwy", $infoarr) ? $infoarr['mendianfwy'] : '';
                $mendianfwytel = array_key_exists("mendianfwytel", $infoarr) ? $infoarr['mendianfwytel'] : '';
            } else {
                $mendian = '';
                $mendianfwy = '';
                $mendianfwytel = '';
            }
            if (array_key_exists("xm", $infoarr)) {
                //$fwinfoarr = json_decode($data2[$i-2]['fwymore']);
                $xm = htmlspecialchars_decode($infoarr['xm']);
                $xm = str_replace('{"xmarr":["', "", $xm);
                $xm = str_replace('","', '-', $xm);
                $xm = str_replace('"],"zjje":"', '-', $xm);
                $xm = str_replace(';总金额', '-总金额', $xm);
                $xm = str_replace('"}', '', $xm);
                // $xms = $infoarr->xm;
                // $xm = $xms->xmarr;
            }

            //获取老人信息
            //$portalPostModel = new PortalPostModel();
            //$post = $portalPostModel->where('id', $data2[$i - 2]['czlrid'])->find();
//            $lrarr = $post['more'];
//            $postCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
//            $postCategoryIds = implode(',', array_keys($data2[$i - 2]['categories']));
//            $flinfo = Db::name('portal_category')->where('id', $postCategoryIds)->find(); //社区

            $flinfo = current($data2[$i - 2]['categories']);
            $dlinfo = [];
            if ($flinfo) {
                $dlinfo = Db::name('portal_category')->where('id', $flinfo['parent_id'])->find(); //街道
            }

            $excel->getActiveSheet()->setCellValue("$letter[0]$i", $i - 1);
            $excel->getActiveSheet()->setCellValue("$letter[1]$i", ' ' . $data2[$i - 2]['post_source']);
            $excel->getActiveSheet()->setCellValue("$letter[2]$i", $data2[$i - 2]['post_title']);
            $excel->getActiveSheet()->setCellValue("$letter[3]$i", $sexArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[4]$i", $olderTypeArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[5]$i", ' ' . $tel);
            $excel->getActiveSheet()->setCellValue("$letter[6]$i", ' ' . @$infoarr['zjnum']);
            $excel->getActiveSheet()->setCellValue("$letter[7]$i", $ageArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[8]$i", $moneyArray[$i - 2]);
            $excel->getActiveSheet()->setCellValue("$letter[9]$i", $dlinfo ? $dlinfo['name'] : '');
            $excel->getActiveSheet()->setCellValue("$letter[10]$i", $flinfo ? $flinfo['name'] : '');
            $excel->getActiveSheet()->setCellValue("$letter[11]$i", $infoarr['add']);
            $excel->getActiveSheet()->setCellValue("$letter[12]$i", $data2[$i - 2]['post_keywords']);
            $excel->getActiveSheet()->setCellValue("$letter[13]$i", isset($xm) ? $xm : '');
            $excel->getActiveSheet()->setCellValue("$letter[14]$i", $data2[$i - 2]['gdstatus']);
            $excel->getActiveSheet()->setCellValue("$letter[15]$i", $mendian);
            $excel->getActiveSheet()->setCellValue("$letter[16]$i", $mendianfwy);
            $excel->getActiveSheet()->setCellValue("$letter[17]$i", ' ' . $mendianfwytel);
            $excel->getActiveSheet()->setCellValue("$letter[18]$i", $data2[$i - 2]['money']);
        }
        //创建Excel输入对象
        $write = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="工单列表.xls"');
        header("Content-Transfer-Encoding:binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");


        $write->save('php://output');

        //     echo $write;
        // $write->save('down/工单列表.xlsx');
        // $down_host = $_SERVER['HTTP_HOST'].'/'; //当前域名
        //生成的excel路径
        // $excelurl=$down_host.'upload/down/工单列表.xlsx';
        // print_r($excelurl);exit();
        // header('location:'.$down_host.'upload/down/工单列表.xlsx');
        //     return $excelurl;
        //exit;
        //print_r($write);exit();
        //return
        $this->success("导出成功");

    }

    public function daochu1()
    {
        header("Location:portal/admin_order/daochu.html");
    }

    public function daochu2()
    {

        //$param = $this->request->param();
        //print_r($param);
        //引入PHPExcel库文件
        //vendor("PHPExcel.PHPExcel");
        //创建对象
        $excel = new PHPExcel();
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q');
        //表头数组
        $tableheader = array('序号', '工单编号', '残疾人姓名', '联系方式', '身份证号', '年龄', '余额', '街道', '社区', '地址', '家政服务项目', '项目明细', '工单状态', '门店', '服务员姓名', '服务员电话', '总价格');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        //表格数组
        // $data = array(
        //     array('1', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('2', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('3', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('4', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('5', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('6', 'B', 'C', 'D', 'E', 'F', 'G'),
        //     array('7', 'B', 'C', 'D', 'E', 'F', 'G'),
        // );
        $portalPostModel = new PortalPostModel();
        //->where('id', 'in', $param['ids'])
        $data2 = Db::name('portal_post')->where('post_type', 5)->where('delete_time', 0)->order("id desc")->select();
        // foreach ($data as $datas) {
        //     Db::name('portal_post')
        //         ->where('id', $datas['id'])
        //         ->update(['money' => 0]);
        // }
        // $tz = M('taizhang');
        // $data2 = $tz->field('type',true)->select();

        // //填充表格信息
        for ($i = 2; $i <= count($data2) + 1; $i++) {
            $infoarr = json_decode($data2[$i - 2]['more']);
            $tel = '';
            if (array_key_exists("tel", $infoarr)) {
                $tel = $infoarr->tel;
            }
            if (array_key_exists("mendian", $infoarr)) {
                //$fwinfoarr = json_decode($data2[$i-2]['fwymore']);
                $mendian = $infoarr->mendian;
                $mendianfwy = array_key_exists("mendianfwy", $infoarr) ? $infoarr->mendianfwy : '';
                $mendianfwytel = array_key_exists("mendianfwytel", $infoarr) ? $infoarr->mendianfwytel : '';
            } else {
                $mendian = '';
                $mendianfwy = '';
                $mendianfwytel = '';
            }
            if (array_key_exists("xm", $infoarr)) {
                //$fwinfoarr = json_decode($data2[$i-2]['fwymore']);
                $xm = htmlspecialchars_decode($infoarr->xm);
                $xm = str_replace('{"xmarr":["', "", $xm);
                $xm = str_replace('","', '-', $xm);
                $xm = str_replace('"],"zjje":"', '-', $xm);
                $xm = str_replace(';总金额', '-总金额', $xm);
                $xm = str_replace('"}', '', $xm);
                // $xms = $infoarr->xm;
                // $xm = $xms->xmarr;
            }

            //获取残疾人信息
            $portalPostModel = new PortalPostModel();
            $post = $portalPostModel->where('id', $data2[$i - 2]['czlrid'])->find();
            $lrarr = $post['more'];
            $postCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
            $postCategoryIds = implode(',', array_keys($postCategories));
            $flinfo = Db::name('portal_category')->where('id', $postCategoryIds)->find(); //社区
            $dlinfo = Db::name('portal_category')->where('id', $flinfo['parent_id'])->find(); //街道


            $excel->getActiveSheet()->setCellValue("$letter[0]$i", $i - 1);
            $excel->getActiveSheet()->setCellValue("$letter[1]$i", $data2[$i - 2]['post_source']);
            $excel->getActiveSheet()->setCellValue("$letter[2]$i", $data2[$i - 2]['post_title']);
            $excel->getActiveSheet()->setCellValue("$letter[3]$i", $tel);
            $excel->getActiveSheet()->setCellValue("$letter[4]$i", $lrarr['zjnum']);
            $excel->getActiveSheet()->setCellValue("$letter[5]$i", $lrarr['age']);
            $excel->getActiveSheet()->setCellValue("$letter[6]$i", $post['money']);
            $excel->getActiveSheet()->setCellValue("$letter[7]$i", $dlinfo['name']);
            $excel->getActiveSheet()->setCellValue("$letter[8]$i", $flinfo['name']);
            $excel->getActiveSheet()->setCellValue("$letter[9]$i", $infoarr->add);
            $excel->getActiveSheet()->setCellValue("$letter[10]$i", $data2[$i - 2]['post_keywords']);
            $excel->getActiveSheet()->setCellValue("$letter[11]$i", $xm);
            $excel->getActiveSheet()->setCellValue("$letter[12]$i", $data2[$i - 2]['gdstatus']);
            $excel->getActiveSheet()->setCellValue("$letter[13]$i", $mendian);
            $excel->getActiveSheet()->setCellValue("$letter[14]$i", $mendianfwy);
            $excel->getActiveSheet()->setCellValue("$letter[15]$i", $mendianfwytel);
            $excel->getActiveSheet()->setCellValue("$letter[16]$i", $data2[$i - 2]['money']);
        }
        //创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        $filename = "工单列表.xlsx";

        $write->save(iconv('utf-8', 'gbk', $filename));
        echo $write;
        $this->success("导出成功");
        // header("Pragma: public");
        // header("Expires: 0");
        // header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        // header("Content-Type:application/force-download");
        // header("Content-Type:application/vnd.ms-execl");
        // header("Content-Type:application/octet-stream");
        // header("Content-Type:application/download");;
        // header('Content-Disposition:attachment;filename="工单列表.xlsx"');
        // header("Content-Transfer-Encoding:binary");
        // header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        // header("Pragma: no-cache");


        // $write->save('php://output');

        //     echo $write;
        // $write->save('down/工单列表.xlsx');
        // $down_host = $_SERVER['HTTP_HOST'].'/'; //当前域名
        //生成的excel路径
        // $excelurl=$down_host.'upload/down/工单列表.xlsx';
        // print_r($excelurl);exit();
        // header('location:'.$down_host.'upload/down/工单列表.xlsx');
        //     return $excelurl;
        //exit;
        //print_r($write);exit();
        //return
        //$this->success("导出成功");

    }

}
